package com.zhangtingshu.controller;

import com.zhangtingshu.pojo.Role;
import com.zhangtingshu.pojo.User;
import com.zhangtingshu.service.RoleService;
import com.zhangtingshu.service.UserService;
import com.zhangtingshu.service.impl.RoleServiceImpl;
import com.zhangtingshu.service.impl.UserServiceImpl;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author zhangtingshu
 * 用户控制器
 */
@Controller
public class UserController {

    Logger logger = Logger.getLogger(UserController.class);

    @Autowired
    private RoleServiceImpl roleService;

    @Autowired
    private UserServiceImpl userService;

    @RequestMapping("/toregist")
    public String toregist(Model model) {
        logger.info("coming...");
        //查询角色集合
        List<Role> roles = roleService.findAll();
        //将角色集合放入作用域中
        model.addAttribute("roles", roles);
        return "regist";
    }

    @RequestMapping("/adduser")
    public String adduser(@ModelAttribute User user) {
        logger.info(user.getName());
        logger.info(user.getPass());
        logger.info(user.getTel());
        logger.info(user.getRid());
        int uid = userService.saveUser(user);
        return "redirect:/tologin.action?uid=" + uid;
    }

    @RequestMapping("/tologin")
    public String tologin(String uid, Model model) {
        model.addAttribute("uid", uid);
        return "login";
    }

    @RequestMapping("/login")
    public String login(@ModelAttribute User user, String captcha, HttpSession session, Model model) {
        //从session中获取验证码
        String simpleCaptcha = String.valueOf(session.getAttribute("simpleCaptcha"));
        logger.info(simpleCaptcha);
        if (captcha.equals(simpleCaptcha)) {
            //开始登录验证
            User currentUser = userService.findByPassAndId(user);
            if (currentUser != null) {//登录成功
                //将当前登录用户放在session中
                session.setAttribute("currentUser", currentUser);
                return "redirect:/list.action";
            } else {
                //用户名或密码输入错误
                model.addAttribute("mess", "用户名或密码输入错误");
                return "login";
            }
        } else {
            //验证码输入错误
            model.addAttribute("mess", "验证码输入错误");
            return "login";
        }
    }

    @RequestMapping("/exit")
    public String exit(HttpSession session) {
        //退出登录
        session.invalidate();
        return "redirect:/list.action";
    }
}
